package com.lczyfz.wisdom.modules.platform.wxutils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.lczyfz.wisdom.common.utils.ResponseCode;
import com.lczyfz.wisdom.common.utils.ServerResponse;
import com.lczyfz.wisdom.modules.platform.constant.Constant;
import org.json.JSONException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Create by css on 2019/9/29
 */
public class SmsUtils {

    private int smsAppId;
    private String smsAppKey;
    private int smsTemplateId;
    private String smsSign;

    public SmsUtils(){
        Properties properties = Constant.getProperties();
        smsAppId = Integer.valueOf(properties.getProperty("smsAppId","0"));
        smsAppKey = properties.getProperty("smsAppKey","");
        smsTemplateId = Integer.valueOf(properties.getProperty("smsTemplateId","0"));
        try {
            smsSign=new String(properties.getProperty("smsSign").getBytes("ISO-8859-1"),"gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }


    /**
     * 发送短信验证码
     * @param phoneNumbers
     */
    public ServerResponse sendMessage(String... phoneNumbers){
        int code = 0;
        String errMsg = "";
        SortedMap<String, String> signParams = new TreeMap<String, String>();
        String verifyCode = "";
        long stamp = System.currentTimeMillis();
        try {
            //生成验证码
            verifyCode = createVerifyCode(true, 6);
            //验证码  有效时间
            String[] params = {verifyCode,"2"};
            SmsSingleSender ssender = new SmsSingleSender(smsAppId, smsAppKey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    smsTemplateId, params, smsSign, "", "");
            System.out.println(result);
            JSONObject jsonObject = JSON.parseObject(result.toString());
            code = (Integer) jsonObject.get("result");
            errMsg = new String(jsonObject.getString("errmsg"));
        } catch (HTTPException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // JSON 解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络 IO 错误
            e.printStackTrace();
        }finally {
            if(code == 0){
                signParams.put("verifyCode", verifyCode);//验证码
                signParams.put("stamp",stamp+"");//时间戳
                String paramStr = CreateSignUtils.compileParams(signParams);
                //获取短信验证码sign
                String sign = CreateSignUtils.createSign("UTF-8", paramStr);
                /*sign += "&stamp="+stamp;*/
                return new ServerResponse(code,UnicodeUtils.unicodetoString(errMsg),sign+"&stamp="+stamp);
            }else {
                return new ServerResponse(code,UnicodeUtils.unicodetoString(errMsg));
            }
        }
    }

    /**
     * 校验验证码
     * @param sign
     * @param verifyCode
     * @param stamp
     * @return
     */
    public ServerResponse checkVerifyCode(String sign,String verifyCode,String stamp){
        ServerResponse serverResponse = null;
        SortedMap<String, String> signParams = new TreeMap<String, String>();
        signParams.put("verifyCode", verifyCode);//验证码
        signParams.put("stamp",stamp+"");//时间戳
        String result = null;
        try {
            signParams.put("verifyCode", verifyCode);//验证码
            signParams.put("stamp",stamp+"");//时间戳
            String paramStr = CreateSignUtils.compileParams(signParams);
            //获取短信验证码sign
            result = CreateSignUtils.createSign("UTF-8", paramStr);
            if(null == verifyCode || "".equals(verifyCode)){
                serverResponse = new ServerResponse(-10001,"验证失败,验证码输入不能为空");
            }else if(null == sign || "".equals(sign)){
                serverResponse = new ServerResponse(-10002,"验证失败,sign不能为空");
            }else if(null == stamp || "".equals(stamp)){
                serverResponse = new ServerResponse(-10003,"验证失败,stamp不能为空");
            }else if(null != result && result.equals(sign)){
                // TODO: 2019/10/1

                serverResponse = new ServerResponse(-10004,"验证成功");
            }
            if(null == serverResponse){
                serverResponse = new ServerResponse(-10005,"验证失败,稍后重试");
            }
            return serverResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return new ServerResponse(-10006,"服务器正忙,请稍后重新验证");
        }
    }

    public void parseRequest(HttpServletRequest request){
        ServletInputStream inputStream = null;
        String result = null;
        try {
            inputStream = request.getInputStream();
            int len = -1;
            while ((len = inputStream.read()) != -1){
                result += len;
            }
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成随机验证码
     * @param numberFlag
     * @param length
     * @return
     */
    public String createVerifyCode (boolean numberFlag, int length){
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);
        return retStr;
    }

}
